﻿package code {
	// HI JOE!!!!
	// This is my main document class that handles the main game
	import flash.display.MovieClip;
	import flash.events.*;
	import flash.geom.Point;
	import flash.utils.getTimer;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	public class Document extends MovieClip {
		var web:Web;		// the main spider web
		var isPaused, doingPaused:Boolean; // isPaused is if the play button should act as a pause button; doingPaused is whether the gamestate is paused
		var pooledPolygons, currentPolygons:Array;  //pooledPolygons is a list of the pre created polygons, currentPolygons is the actual polygon
		var currentTime, score:int;		// currentTime is the time running in the background for triggering; score keeps track of total points
		var numToDrop:Number;	// num to drop is the number to drop each phase
		var previousTime, gotTime:Number;
		var xmlFile:String = "webData.xml";
		var xml:XML;
		var xmlLoader:URLLoader;
		
		
		//const section
		const POLYGONS_TO_MAKE:int = 50; // the total number of polygons to make
		const BASE_SPEED:int = 5;	// the base random amount for polygons to fall at
		const MAX_SPEED:int = 15;	// the max random speed for polygons to fall at
		
		const BASE_SIZE:Number = 1;	 // the base size to make the polygon
		const MAX_SIZE:Number = 1.5; // the max size to make the polygon
		
		const BASE_SIDES:int = 3;	// the base number of sides for the polygon
		const MAX_SIDES:int = 10;	// the max number of sides for a polygon
		
		const WEB_X = 40;			// the location of the webx
		const WEB_Y = 480;			// the location of the weby
		
		public function Document() {
			isPaused = false;
			doingPaused = false;
			
			pooledPolygons = new Array();
			currentPolygons = new Array();
			
			currentTime = 0;
			score = 0;
			numToDrop = 1;
			
			play_Btn.addEventListener(MouseEvent.CLICK, doPlay);
			pause_Btn.addEventListener(MouseEvent.CLICK, doPause); //Begin listening for Pause Button
			reset_Btn.addEventListener(MouseEvent.CLICK, doReset);
			
			previousTime = 0;
			
			xmlLoader = new URLLoader();
			xml = new XML();
			
			loseBox.alpha = 0;
			
			init();
			
		}
		
		private function init(){
			xmlLoader.addEventListener(Event.COMPLETE, loadXML);  // xml to readin  web information
			xmlLoader.load(new URLRequest(xmlFile));
			generatePolygons();
		}
		
		private function loadXML(e:Event){
			xml = new XML(e.target.data);
			web = new Web(xml.sides, xml.recurseTimes, xml.radius);  // createa a new web(sides, timesToRecurse, radius)
			addChild(web);
		}
		
		// generates the polygons for the game
		private function generatePolygons(){
			var randomX:int;
			var yPos:int = -50;
			
			for(var i:int = 0; i < POLYGONS_TO_MAKE; i++){
				var numOfSides = Math.random() * MAX_SIDES + BASE_SIDES;  // creates the number of sides
				
				randomX = getRandomX();  // gets the random x in correct bounds
				var speed = Math.random() * MAX_SPEED + BASE_SPEED; // gets the speed for the objects
				var size = Math.random() * MAX_SIZE + BASE_SIZE;
				
				var tempPoly = new Polygon(numOfSides, new Vertex(randomX, yPos, 0, 0), speed, size);
				tempPoly.x = randomX;
				pooledPolygons.push(tempPoly);  // pools the polygon
				addChild(tempPoly);
			}
		}
		
		// gets a random x position not directly above the spider web
		private function getRandomX():Number{
			var numberWorks:Boolean = false;
			var randomX:int;
			while(!numberWorks){
				randomX = Math.random() * 450;
				if((randomX > 0 && randomX < WEB_X)  || (randomX > 400 && randomX < 540)){  // range not to go in
					numberWorks = true;
				}
			}
			return randomX;
		}
		
		// does play button
		private function doPlay(e:Event){
			if(!doingPaused){
				addEventListener(Event.ENTER_FRAME, update); // makes the event stop working
				doingPaused = true;
				isPaused = false;
			}
			else{
				web.playWeb();
				addEventListener(Event.ENTER_FRAME, update);
				isPaused = false;
			}
		}
		
		// pauses the game
		private function doPause(e:Event){
			if(!isPaused){
				web.pauseWeb();
				isPaused = true;
				removeEventListener(Event.ENTER_FRAME, update);
			}
			else{
				web.playWeb();
				isPaused = false;
				addEventListener(Event.ENTER_FRAME, update);
			}
		}
		
		// reset method
		private function doReset(e:Event){
			web.resetWeb();		// resets the web
			doingPaused = false;
			score = 0;
			scoreText.text = "Score: " + score;
			numToDrop = 1;
			removeEventListener(Event.ENTER_FRAME, update);
			
			if(pooledPolygons != null && pooledPolygons.length > 1)
				clearArray(pooledPolygons);  // clears the pooled polygons
			if(currentPolygons != null && currentPolygons.length > 1)
				clearArray(currentPolygons);  // clears the pooled polygons
			pooledPolygons = new Array();
			currentPolygons = new Array();
			generatePolygons();

			
		}
		
		// clears an array passed 
		private function clearArray(arrayToClear:Array){
			for each(var o:Polygon in arrayToClear){
				if(o != null)
					removeChild(o);
			}
		}
		
		// updaets the game
		private function update(e:Event){
			gotTime = getTimer();
			var timeDif = gotTime - previousTime;
			previousTime = gotTime;
			
			// lets the player know the game state
			if(pooledPolygons.length <= 0)
				loseBox.alpha = 1;
			
			else
				loseBox.alpha = 0;
			
			remainingText.text = "Polygons Remaining: " + pooledPolygons.length;  // updates the polygons remaining
			dropPolygons(timeDif);
			checkCollision();
		}
		
		// drops polygons at an interval
		private function dropPolygons(timeDif:Number){
			if(timeDif > 1)
				timeDif = 1;
			if(currentTime % 200 == 0) // drops every 200 
			{
				for(var i:int = 0; i < numToDrop; i++){
					currentPolygons.push(pooledPolygons.pop());
				}
				numToDrop *= 1.5;  // incresese numToDrop by 1.5
			}
			for each(var p:Polygon in currentPolygons){
				if(p != null)
					p.y += p.speed * timeDif;
			}
			
			currentTime++;
		}
		
		
		// checks collision of every vertex against all the polygons on the screen
		private function checkCollision(){
			for(var i:int = 0; i < currentPolygons.length; i++){//each(var p:Polygon in currentPolygons){
				for each(var v:Vertex in web.webVertices){
					if(currentPolygons[i] != null && v.hitTestObject(currentPolygons[i])){
						var scoreModifier:int;
						if(currentPolygons[i].size < 1){
							scoreModifier = currentPolygons[i].size * 10;
						}
						else{
							scoreModifier = currentPolygons[i].size - 1;
						}
							
						
						score += currentPolygons[i].speed + scoreModifier;
						scoreText.text = "Score: " + score;  // updates the score if hit based on speed
						web.tempVert.stopDrag();	// snaps the web back if collided
						web.tempVert.alreadyChecked = false;
						
						removeChild(currentPolygons[i]);
						currentPolygons.splice(i, 1);
						i--;
					}
				}

			}
		}
		
	}
	
}
